#!/usr/bin/env python

# Copyright 2011 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Street Identity Demo Relying Party Model."""

from google.appengine.ext import db
import datetime
import time
from lib.oauth2client.appengine import CredentialsProperty

__author__ = "Maciej Machulak"
__maintainer__ = "Maciej Machulak"
__email__ = "mmachulak@google.com"

__copyright__ = "Copyright 2011, Google Inc."
__license__ = "Apache License 2.0"
__version__ = "0.1"
__status__ = "Prototype"

SIMPLE_TYPES = (int, long, float, bool, dict, basestring, list)

class User(db.Model):
    username = db.StringProperty(required = True)
    display_name = db.StringProperty(required = True)  
    email = db.StringProperty(required = True)
    def to_dict(self):
      return to_dict(self)

class Session(db.Model):
    id = db.StringProperty(required = True)
    user = db.ReferenceProperty(User,required = True)
    verified = db.BooleanProperty(default = False)
    
class Address(db.Model):
    address = db.StringProperty(required = True)
    type = db.StringProperty(choices=('home','office'))
    user = db.ReferenceProperty(User,collection_name='adress_list',required=True)
    provider = db.StringProperty(required = True)
    def to_dict(self):
      return to_dict(self)
    
class Credentials(db.Model):
    credentials = CredentialsProperty()

def to_dict(model):
    output = {}
    for key, prop in model.properties().iteritems():
        value = getattr(model, key)

        if value is None or isinstance(value, SIMPLE_TYPES):
            output[key] = value
        elif isinstance(value, datetime.date):
            # Convert date/datetime to ms-since-epoch ("new Date()").
            ms = time.mktime(value.utctimetuple()) * 1000
            ms += getattr(value, 'microseconds', 0) / 1000
            output[key] = int(ms)
        elif isinstance(value, db.GeoPt):
            output[key] = {'lat': value.lat, 'lon': value.lon}
        elif isinstance(value, db.Model):
            output[key] = to_dict(value)
        else:
            raise ValueError('cannot encode ' + repr(prop))
    return output         